import numpy as np
from itertools import product
import pandas as pd
import pandas as pd

class ProductionDecisionModel:
    def __init__(self):
        # 决策变量: x1,x2,x3,x4 ∈ {0,1}
        self.decision_vars = ['x1', 'x2', 'x3', 'x4']
        
    def set_parameters(self, p1, p2, pc, c1b, c2b, c1t, c2t, cpt, ca, cd, ce, R):
        """设置参数"""
        self.p1, self.p2, self.pc = p1, p2, pc  # 次品率
        self.c1b, self.c2b = c1b, c2b  # 购买成本
        self.c1t, self.c2t, self.cpt = c1t, c2t, cpt  # 检测成本
        self.ca, self.cd, self.ce = ca, cd, ce  # 装配、拆解、换货成本
        self.R = R  # 市场售价
    
    def calculate_pass_rate(self, x1, x2, x3):
        """计算合格率"""
        # 当检测时，合格率 = (1-p1*x1)(1-p2*x2)(1-pc*x3)
        # 当不检测时，合格率 = (1-p1)(1-p2)(1-pc)
        if x1 == 0 and x2 == 0 and x3 == 0:
            # 全部不检测时，合格率反映真实次品率
            return (1 - self.p1) * (1 - self.p2) * (1 - self.pc)
        else:
            # 有检测时，按检测结果计算
            return (1 - self.p1 * x1) * (1 - self.p2 * x2) * (1 - self.pc * x3)
    
    def calculate_total_cost(self, x1, x2, x3, x4):
        """计算总期望成本"""
        # 购买成本
        purchase_cost = self.c1b + self.c2b
        
        # 检测成本
        inspection_cost = x1 * self.c1t + x2 * self.c2t + x3 * self.cpt
        
        # 装配成本
        assembly_cost = self.ca
        
        # 拆解成本
        disassembly_cost = x3 * self.pc * x4 * self.cd
        
        # 换货损失
        # 根据公式：c_e ⋅ (1 - x_3) [1 - (1 - p_1 x_1)(1 - p_2 x_2)]
        if x3 == 0:  # 成品不检测时
            # 计算零件合格概率
            part1_qual_prob = 1 - self.p1 * x1  # (1 - p_1 x_1)
            part2_qual_prob = 1 - self.p2 * x2  # (1 - p_2 x_2)
            
            # 不合格产品进入市场的概率
            defect_prob = 1 - part1_qual_prob * part2_qual_prob  # [1 - (1 - p_1 x_1)(1 - p_2 x_2)]
            
            # 调换损失
            replacement_loss = defect_prob * self.ce
        else:
            replacement_loss = 0.0  # 成品检测时，不会有调换损失
        
        # 收入
        pass_rate = self.calculate_pass_rate(x1, x2, x3)
        revenue = pass_rate * self.R
        
        # 总成本
        total_cost = purchase_cost + inspection_cost + assembly_cost + disassembly_cost + replacement_loss - revenue
        
        return total_cost, pass_rate, {
            'purchase_cost': purchase_cost,
            'inspection_cost': inspection_cost,
            'assembly_cost': assembly_cost,
            'disassembly_cost': disassembly_cost,
            'replacement_loss': replacement_loss,
            'revenue': revenue
        }
    
    def find_optimal_decision(self):
        """寻找最优决策"""
        min_cost = float('inf')
        optimal_decision = None
        
        # 枚举所有决策组合
        for x1, x2, x3, x4 in product([0, 1], repeat=4):
            total_cost, pass_rate, cost_details = self.calculate_total_cost(x1, x2, x3, x4)
            
            if total_cost < min_cost:
                min_cost = total_cost
                optimal_decision = (x1, x2, x3, x4)
        
        return optimal_decision, min_cost

def print_all_decisions(situation_num, params):
    """打印所有16种决策组合"""
    print(f"\n=== 情形{situation_num} 所有决策组合 ===")
    print(f"参数: p1={params['p1']:.1%}, p2={params['p2']:.1%}, pc={params['pc']:.1%}")
    print(f"成本: c1t={params['c1t']}, c2t={params['c2t']}, cpt={params['cpt']}, ce={params['ce']}")
    print(f"{'决策':>8} {'零件1':>6} {'零件2':>6} {'成品':>6} {'拆解':>6} {'总成本':>10} {'合格率':>8} {'购买':>8} {'检测':>8} {'装配':>8} {'拆解':>8} {'换货':>8} {'收入':>8}")
    print("-" * 120)
    
    model = ProductionDecisionModel()
    model.set_parameters(**params)
    
    all_costs = []
    all_data = []
    for x1, x2, x3, x4 in product([0, 1], repeat=4):
        total_cost, pass_rate, cost_details = model.calculate_total_cost(x1, x2, x3, x4)
        all_costs.append(total_cost)
        
        decision_str = f"{x1}{x2}{x3}{x4}"
        print(f"{decision_str:>8} {'是' if x1 else '否':>6} {'是' if x2 else '否':>6} {'是' if x3 else '否':>6} {'是' if x4 else '否':>6} "
              f"{total_cost:>10.2f} {pass_rate:>7.1%} {cost_details['purchase_cost']:>8.2f} {cost_details['inspection_cost']:>8.2f} "
              f"{cost_details['assembly_cost']:>8.2f} {cost_details['disassembly_cost']:>8.2f} {cost_details['replacement_loss']:>8.2f} {cost_details['revenue']:>8.2f}")
        
        # 收集数据用于Excel导出
        all_data.append({
            '情形': situation_num,
            '决策': decision_str,
            '零件1检测': '是' if x1 else '否',
            '零件2检测': '是' if x2 else '否',
            '成品检测': '是' if x3 else '否',
            '拆解': '是' if x4 else '否',
            '总成本': total_cost,
            '合格率': pass_rate,
            '购买成本': cost_details['purchase_cost'],
            '检测成本': cost_details['inspection_cost'],
            '装配成本': cost_details['assembly_cost'],
            '拆解成本': cost_details['disassembly_cost'],
            '换货损失': cost_details['replacement_loss'],
            '收入': cost_details['revenue']
        })
    
    # 找到最优决策
    min_cost = min(all_costs)
    optimal_indices = [i for i, cost in enumerate(all_costs) if cost == min_cost]
    
    print("-" * 120)
    print(f"最优决策:")
    for i, (x1, x2, x3, x4) in enumerate(product([0, 1], repeat=4)):
        if i in optimal_indices:
            decision_str = f"{x1}{x2}{x3}{x4}"
            print(f"  决策{decision_str}: 零件1{'是' if x1 else '否'}, 零件2{'是' if x2 else '否'}, 成品{'是' if x3 else '否'}, 拆解{'是' if x4 else '否'}")
    print(f"最优总成本: {min_cost:.2f}")
    
    return min_cost, all_data

def export_to_excel(all_results_data, filename='企业生产决策分析.xlsx'):
    """导出所有结果到Excel文件"""
    # 创建DataFrame
    df = pd.DataFrame(all_results_data)
    
    # 创建Excel写入器
    with pd.ExcelWriter(filename, engine='openpyxl') as writer:
        # 写入详细数据
        df.to_excel(writer, sheet_name='详细决策数据', index=False)
        
        # 创建汇总表
        summary_data = []
        for situation_num in range(1, 7):
            situation_data = df[df['情形'] == situation_num]
            min_cost_row = situation_data.loc[situation_data['总成本'].idxmin()]
            summary_data.append({
                '情形': situation_num,
                '最优决策': min_cost_row['决策'],
                '最优总成本': min_cost_row['总成本'],
                '最优合格率': min_cost_row['合格率'],
                '零件1检测': min_cost_row['零件1检测'],
                '零件2检测': min_cost_row['零件2检测'],
                '成品检测': min_cost_row['成品检测'],
                '拆解': min_cost_row['拆解']
            })
        
        summary_df = pd.DataFrame(summary_data)
        summary_df.to_excel(writer, sheet_name='最优决策汇总', index=False)
        
        # 创建参数表
        params_data = {
            '情形': [1, 2, 3, 4, 5, 6],
            '零件1次品率': ['10%', '20%', '10%', '20%', '10%', '5%'],
            '零件2次品率': ['10%', '20%', '10%', '20%', '20%', '5%'],
            '成品次品率': ['10%', '20%', '10%', '20%', '10%', '5%'],
            '零件1检测成本': [2, 2, 2, 1, 8, 2],
            '零件2检测成本': [3, 3, 3, 1, 1, 3],
            '成品检测成本': [3, 3, 3, 2, 2, 3],
            '换货损失': [6, 6, 30, 30, 10, 10],
            '拆解成本': [5, 5, 5, 5, 5, 40]
        }
        params_df = pd.DataFrame(params_data)
        params_df.to_excel(writer, sheet_name='参数设置', index=False)
    
    print(f"\nExcel文件已导出: {filename}")
    print("包含以下工作表:")
    print("1. 详细决策数据 - 所有96种决策组合的详细信息")
    print("2. 最优决策汇总 - 6种情形的最优决策")
    print("3. 参数设置 - 各情形的参数配置")

if __name__ == "__main__":
    # 情形数据
    situations = {
        1: {'p1': 0.1, 'p2': 0.1, 'pc': 0.1, 'c1b': 4, 'c2b': 18, 'c1t': 2, 'c2t': 3, 'cpt': 3, 'ca': 6, 'cd': 5, 'ce': 6, 'R': 56},
        2: {'p1': 0.2, 'p2': 0.2, 'pc': 0.2, 'c1b': 4, 'c2b': 18, 'c1t': 2, 'c2t': 3, 'cpt': 3, 'ca': 6, 'cd': 5, 'ce': 6, 'R': 56},
        3: {'p1': 0.1, 'p2': 0.1, 'pc': 0.1, 'c1b': 4, 'c2b': 18, 'c1t': 2, 'c2t': 3, 'cpt': 3, 'ca': 6, 'cd': 5, 'ce': 30, 'R': 56},
        4: {'p1': 0.2, 'p2': 0.2, 'pc': 0.2, 'c1b': 4, 'c2b': 18, 'c1t': 1, 'c2t': 1, 'cpt': 2, 'ca': 6, 'cd': 5, 'ce': 30, 'R': 56},
        5: {'p1': 0.1, 'p2': 0.2, 'pc': 0.1, 'c1b': 4, 'c2b': 18, 'c1t': 8, 'c2t': 1, 'cpt': 2, 'ca': 6, 'cd': 5, 'ce': 10, 'R': 56},
        6: {'p1': 0.05, 'p2': 0.05, 'pc': 0.05, 'c1b': 4, 'c2b': 18, 'c1t': 2, 'c2t': 3, 'cpt': 3, 'ca': 6, 'cd': 40, 'ce': 10, 'R': 56}
    }
    
    print("=== 企业生产决策优化分析 ===")
    print("分析所有16种决策组合在6种情形下的表现")
    print("决策编码: x1x2x3x4 (0=否, 1=是)")
    print("=" * 120)
    
    results = {}
    all_results_data = []
    for situation_num, params in situations.items():
        min_cost, situation_data = print_all_decisions(situation_num, params)
        results[situation_num] = min_cost
        all_results_data.extend(situation_data)
    
    print(f"\n=== 各情形最优成本汇总 ===")
    for situation_num, min_cost in results.items():
        print(f"情形{situation_num}: {min_cost:.2f}")
    
    # 导出到Excel
    export_to_excel(all_results_data)
